package com.farsight.leo.fssmartlock.activities;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import com.farsight.leo.fssmartlock.Constants;
import com.farsight.leo.fssmartlock.R;
import com.farsight.leo.fssmartlock.bases.BaseActivity;
import com.farsight.leo.fssmartlock.bases.BaseApplication;
import com.farsight.leo.fssmartlock.db.DeviceEntity;
import com.farsight.leo.fssmartlock.mqtt.MqttConnection;
import com.farsight.leo.fssmartlock.net.OkHttpHelper;
import com.farsight.leo.fssmartlock.net.bases.BaseOkHttpCallback;
import com.farsight.leo.fssmartlock.net.bean.DeviceData;
import com.farsight.leo.fssmartlock.net.bean.UserData;
import com.farsight.leo.fssmartlock.utils.LogUtils;
import com.farsight.leo.fssmartlock.utils.ToastUtils;

import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatTextView;
import de.hdodenhof.circleimageview.CircleImageView;

public class PostLoginActivity extends BaseActivity implements View.OnClickListener, MqttConnection.Callback {

    private AppCompatTextView mTvUserName;
    private AppCompatButton mBtnAddDev;
    private AppCompatButton mBtnGenAuthCode;
    private CircleImageView mCivOpenLock;
    private AppCompatButton mBtnAuthCodeList;
    private AppCompatButton mBtnSwapDevice;
    private UserData mUserData;
    private boolean isOpen = false;
    private int mMessageId;
    private MqttConnection mMqttConnection;

    public static void start(Context context) {
        Intent starter = new Intent(context, PostLoginActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected int set_layout_id() {
        return R.layout.activity_post_login;
    }

    @Override
    protected void initData() {
        mUserData = BaseApplication.getUserData();
        mMqttConnection = new MqttConnection();
    }

    @Override
    protected void initView() {
        mTvUserName = findViewById(R.id.activity_post_login_tv_user_name);
        mCivOpenLock = findViewById(R.id.activity_post_login_civ_toggle_lock);
        mBtnAddDev = findViewById(R.id.activity_post_login_btn_register_device);
        mBtnGenAuthCode = findViewById(R.id.activity_post_login_btn_gen_auth_code);
        mBtnAuthCodeList = findViewById(R.id.activity_post_login_btn_check_auth_code);
        mBtnSwapDevice = findViewById(R.id.activity_post_login_btn_synchronize_device_from_server);

        mTvUserName.setText(mUserData.getUser_name());

    }

    @Override
    protected void initListeners() {
        mBtnAuthCodeList.setOnClickListener(this);
        mBtnGenAuthCode.setOnClickListener(this);
        mBtnAddDev.setOnClickListener(this);
        mCivOpenLock.setOnClickListener(this);
        mBtnSwapDevice.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mMqttConnection.connect(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        mMqttConnection.disconnect();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.activity_post_login_btn_register_device:
                AddDeviceActivity.start(this);
                break;
            case R.id.activity_post_login_btn_gen_auth_code:
                GenAuthCodeActivity.start(this);
                break;
            case R.id.activity_post_login_btn_check_auth_code:
                AuthCodeListActivity.start(this);
                break;
            case R.id.activity_post_login_civ_toggle_lock:
                toggleDevice();
                break;
            case R.id.activity_post_login_btn_synchronize_device_from_server:
                ActivityDeviceList.start(this);
                break;
            default:
                break;
        }
    }

    private void toggleDevice() {
        DeviceEntity deviceEntity = BaseApplication.getDeviceDb().getDeviceDao().query(BaseApplication.getUserData().getUser_id());
        if (deviceEntity == null) {
            ToastUtils.showToast(getString(R.string.bind_device_first));
            return;
        }
        int newState = isOpen ? 0 : 1;
        DeviceData deviceData = new DeviceData();
        deviceData.setDevice_id(deviceEntity.getId());
        deviceData.setUser_id(deviceEntity.getUserId());
        deviceData.setMac_address(deviceEntity.getMacAddress());
        deviceData.setDevice_status(newState);

        isOpen = !isOpen;
        if (isOpen) {
            mCivOpenLock.setImageResource(R.drawable.ic_lock_open_green_24dp);
        } else {
            mCivOpenLock.setImageResource(R.drawable.ic_lock_outline_green_24dp);
        }
        IMqttDeliveryToken iMqttDeliveryToken = null;
        try {
            iMqttDeliveryToken = mMqttConnection.publish(
                    deviceEntity.getMacAddress(), Constants.MQTT_TITLE_LOCK_STATUS, String.valueOf(newState));
            iMqttDeliveryToken.setActionCallback(new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    LogUtils.log("setActionCallback ok");
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    LogUtils.log("setActionCallback failure");

                }
            });
            mMessageId = iMqttDeliveryToken.getMessageId();
            LogUtils.log("send mqtt msg id=" + mMessageId);
        } catch (MqttException e) {
            e.printStackTrace();
        }


        OkHttpHelper.getInstance().controlDevice(deviceData, new BaseOkHttpCallback<DeviceData>() {
            @Override
            public void onError(String err) {

            }

            @Override
            public void onSuccess(DeviceData result) {

            }
        });


    }

    @Override
    public void onError(String msg) {
        ToastUtils.showToast(msg);
        LogUtils.log("mqtt onError" + msg);
    }

    @Override
    public void onConnectSuccess(IMqttToken asyncActionToken) {
        try {
            mMqttConnection.clearLastRetainMsg();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void connectionLost(Throwable cause) {
        ToastUtils.showToast("mqtt connectionLost");
        LogUtils.log("mqtt connectionLost");
        if (cause == null)
            return;
        String msg = cause.getMessage();
        if (!TextUtils.isEmpty(msg)) {
            LogUtils.log(msg);
        } else {
            msg = cause.getLocalizedMessage();
            if (msg != null) {
                LogUtils.log(msg);
            }
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String data = new String(message.getPayload());
        if (!TextUtils.isEmpty(data)) {
            String[] strings = data.split("%%%&&&");
            if (strings.length == 3) {
                String device_address = strings[0];
                String title = strings[1];
                String device_status = strings[2];
                DeviceEntity entity = BaseApplication.getDeviceDb().getDeviceDao().query(mUserData.getUser_id());
                if (entity != null && entity.getMacAddress().equals(device_address)
                        && title.equals("LOCK_STATUS")) {
                    Integer status = Integer.valueOf(device_status);
                    if (status == 1) {
                        isOpen = true;
                        mCivOpenLock.setImageResource(R.drawable.ic_lock_open_green_24dp);
                        ToastUtils.showToast(getString(R.string.door_open));
                    } else if (status == 0) {
                        isOpen = false;
                        mCivOpenLock.setImageResource(R.drawable.ic_lock_outline_green_24dp);
                        ToastUtils.showToast(getString(R.string.door_close));
                    }
                }
            }
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        //        try {
        //            MqttMessage message = token.getMessage();
        //            int id =token.getMessageId();
        //            LogUtils.log("deliveryComplete id="+id);
        //            if (id == mMessageId) {
        //                LogUtils.log("msg delivered!");
        //            }
        //        } catch (MqttException e) {
        //            e.printStackTrace();
        //        }
    }

    public void toMonitoringActivity(View view) {
        DeviceEntity deviceEntity = BaseApplication.getDeviceDb().getDeviceDao().query(BaseApplication.getUserData().getUser_id());
        if (deviceEntity == null) {
            ToastUtils.showToast(getString(R.string.bind_device_first));
            return;
        }
        MonitoringActivity.start(this, deviceEntity.getMacAddress());
    }
}
